<?php
namespace app\common\util;

use DateTime;

class ImageHelper
{
    public static function urlRoot($dir)
    {
        return env('app_public', '') . "/uploads/$dir/";
    }

    public static function pathRoot($dir)
    {
        return env('root_path') . "public/uploads/$dir/";
    }

    /**
     * args = [
     *   'id' => 123,
     *   'ext' => 'png'
     * ]
     */
    public static function buildName($format, $args)
    {
        $input = $format;
        // 随机数
        $input = preg_replace_callback(
            '/\[rand:(\d+)\]/',
            function ($matches) {
                $len = intval($matches[1]);
                $str = '';
                for ($i = 0; $i < $len; $i++) {
                    $str .= rand(0, 9);
                }
                return $str;
            },
            $input
        );
        // ID
        $input = preg_replace_callback(
            '/\[id(:(\d+))?\]/',
            function ($matches) use ($args) {
                if (isset($matches[1])) {
                    $len = intval($matches[2]);
                    $id = $args['id'];
                    $f = '%0' . $len . 'd';
                    return sprintf($f, $id);
                } else {
                    return sprintf('%d', $args['id']);
                }
            },
            $input
        );
        // EXT
        $input = preg_replace_callback(
            '/\[ext\]/',
            function ($matches) use ($args) {
                return $args['ext'];
            },
            $input
        );
        // 时间日期
        $input = preg_replace_callback(
            '/\[(date|time|datetime):(.+)\]/',
            function ($matches) {
                $f = $matches[2];
                $now = new DateTime();
                return $now->format($f);
            },
            $input
        );
        return $input;
    }

    /**
     * args = [
     *   'id' => 123,
     *   'ext' => 'png',
     *   'dir' => 'avatar',
     * ]
     */
    public static function buildUnusedName($format, $args)
    {
        $path = static::pathRoot($args['dir']);
        for ($i = 0; $i < 20; $i++) {
            $name = static::buildName($format, $args);
            if (!file_exists($path . $name)) {
                return $name;
            }
        }
        error('无法创建此格式的文件名' . $format);
    }
}
